<template>
  <!-- 所属分类 -->
  <!-- 也可以查询其他的，只需要修改payload -->

  <el-cascader
    style="width: 100%"
    v-model="selectvalue"
    v-bind="$attrs"
    :show-all-levels="false"
    :options="options"
    :props="cascaderProps"
    @change="handleChange"
    clearable
  >
  </el-cascader>
</template>

<script>
import utils from "@/utils";
import { queryDictDataTree } from "@/api/common";

export default {
  props: {
    value: {
      required: true,
    },
    returnAll: {
      type: Boolean,
      default: false,
    },
    url: {
      type: Function,
    },
    payload: {
      type: Object | Array,
      default: () => {
        return {
          dictType: "SERVICE_CATGORY",
        };
      },
    },
    cascaderProps: {
      type: Object | Array,
      default: () => {
        return {
          children: "subDictDataList",
          label: "name",
          value: "code",
        };
      },
    },
    cacheValue: String,
  },
  data() {
    return {
      selectvalue: this.value,
      options: [],
    };
  },
  watch: {
    value(newValue, oldValue) {
      this.selectvalue = newValue;
    },
  },
  mounted() {
    this.queryData();
  },
  methods: {
    async queryData() {
      // 从url获取
      let cacheValueData = utils.getsessionStorage(this.cacheValue); // 取缓存数据

      // 有缓存
      if(this.cacheValue){
        if (cacheValueData && cacheValueData.length > 0) {
          this.options = cacheValueData;
          return false
        }
      }

      try {
        let res;
        if (this.url) {
          res = await this.url({
            ...this.payload,
          });
        } else {
          res = await queryDictDataTree({
            ...this.payload,
          });
        }
        this.options = res.returnObj;

        if (this.cacheValue) {
          // 缓存请求的数据
          utils.setsessionStorage(this.cacheValue, res.returnObj);
        }
      } catch (error) {
        console.log(error);
      }
    },
    handleChange(val) {
      if (this.returnAll) {
        this.$emit("input", val);
      } else {
        if (val && val.length > 0) {
          // 取最后一个
          this.$emit("input", val[val.length - 1]);
        } else {
          this.$emit("input", '');
        }
      }

      // change事件
      // this.$emit("change", {
      //   value: val,
      //   row,
      // });
    },
  },
};
</script>

<style lang="scss" scoped></style>
